package com.sjgtw.cloud.job.service.impl;

import com.sjgtw.cloud.common.core.constant.ScheduleConstants;
import com.sjgtw.cloud.common.core.exception.job.TaskException;
import com.sjgtw.cloud.job.common.utils.CronUtils;
import com.sjgtw.cloud.job.common.utils.ScheduleUtils;
import com.sjgtw.cloud.job.domain.SysJob;
import com.sjgtw.cloud.job.mapper.SysJobMapper;
import com.sjgtw.cloud.job.service.ISysJobService;

import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * <p>Title: 定时任务信息处理--服务层--接口实现</p>
 * <p>Description: </p>
 *
* @author Admin
 * @date 2020-7-7
 */
@Service
public class SysJobServiceImpl implements ISysJobService {
	
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private SysJobMapper jobMapper;

    /**
     * <p>Title: 初始化定时任务的定时器；</p>
     * <p>Description: 项目启动时启动本定时器；* 注：不允许修改数据库中ID和任务组名</p>
     *
     * @throws SchedulerException
     * @throws TaskException
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJob> jobList = jobMapper.selectJobAll();
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * <p>Title: 获取quartz调度器的计划任务</p>
     * <p>Description: </p>
     *
     * @param job 调度信息
     * @return 调度任务集合
     */
    @Override
    public List<SysJob> selectJobList(SysJob job) {
        return jobMapper.selectJobList(job);
    }

    /**
     * <p>Title: 通过调度任务ID查询调度信息</p>
     * <p>Description: </p>
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJob selectJobById(Long jobId) {
        return jobMapper.selectJobById(jobId);
    }

    /**
     * <p>Title: 暂停任务</p>
     * <p>Description: </p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * <p>Title: 恢复任务</p>
     * <p>Description: </p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * <p>Title: 删除任务</p>
     * <p>Description: 删除任务后，所对应的trigger也将被删除</p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = jobMapper.deleteJobById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * <p>Title: 批量删除调度信息</p>
     * <p>Description: 删除任务后，所对应的trigger也将被删除</p>
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SysJob job = jobMapper.selectJobById(jobId);
            deleteJob(job);
        }
    }

    /**
     * <p>Title: 修改任务调度状态</p>
     * <p>Description: </p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws SchedulerException {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * <p>Title: 立即运行任务</p>
     * <p>Description: </p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJob job) throws SchedulerException {
    	boolean result = false;
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * <p>Title: 新增任务</p>
     * <p>Description: </p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insertJob(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * <p>Title: 更新任务</p>
     * <p>Description: 更新任务的时间表达式</p>
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJob job) throws SchedulerException, TaskException {
        SysJob properties = selectJobById(job.getJobId());
        int rows = jobMapper.updateJob(job);
        if (rows > 0) {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * <p>Title: 更新任务</p>
     * <p>Description: </p>
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     * @throws SchedulerException
     * @throws TaskException
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * <p>Title: 校验cron表达式是否有效</p>
     * <p>Description: </p>
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }
}